package com.quasar.hpatient.view.record;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.model.custommodel.TemperatureTableItem;
import com.quasar.hpatient.model.custommodel.Trouble;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.DurationInfodb;
import com.quasar.hpatient.model.litePalmodel.TroubleInfodb;
import com.quasar.hpatient.model.medicalmodel.DiscomfortData;
import com.quasar.hpatient.onInterface.OnDataResultListener;
import com.quasar.hpatient.presenter.DiscomfortPresenter;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.adapter.EventAdapter;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.rey.material.widget.EditText;
import com.vise.log.ViseLog;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 事件
 */
@OptionsMenu(R.menu.menu_submit)
@EActivity(R.layout.activity_event)
public class EventActivity extends BaseActivity implements OnDataResultListener {

    private DiscomfortPresenter discomfortPresenter;
    //读取不适时长信息
    final List<DurationInfodb> DurationInfoList = MainAppliaction.getInstance().getDurationinfoList();
    //读取不适症状
    final List<TroubleInfodb> TroubleinfoList = MainAppliaction.getInstance().getTroubleInfoList();
    List<String> TroubleName = new ArrayList<>();
    SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String When = null;
    //是否是化验单界面跳转过来的
    @Extra
    String TimeDate;
    //定义当前不是症状日期
    String longTime;
    private EventAdapter eventAdapter;

    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    //症状描述信息
    @ViewById(R.id.et_describe)
    EditText et_describe;
    //单选(不适时长选择)
    @ViewById(R.id.id_flowlayout)
    TagFlowLayout id_flowlayout;

    //多选(不适症状选择)
    @ViewById(R.id.id_multiselect)
    TagFlowLayout id_multiselect;
    @ViewById(R.id.rv_list)
    RecyclerView rv_list;

    @ViewById(R.id.et_custom)
    android.widget.EditText et_custom;

    @AfterViews
    void init() {
        initView();
        initData();

        ViseLog.d("截取后的日期为"+TimeZoneUtil.sdf.format(new Date()).substring(10,TimeZoneUtil.sdf.format(new Date()).length()));
    }
    TagAdapter tagAdapter;
    TagAdapter MultiselectAdapter;
    @Override
    protected void initView() {
        initToolbar();

        //如果传过来的时间为空则获取当前时间
        if (TimeDate != null) {
            longTime = TimeDate;
        } else {
            longTime = formatTime.format(new Date());
        }

        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);

        //单选
        final LayoutInflater mInflater = LayoutInflater.from(this);
        tagAdapter=new TagAdapter<DurationInfodb>(DurationInfoList) {
            @Override
            public View getView(FlowLayout parent, int position, DurationInfodb s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.tv,
                        id_flowlayout, false);
                tv.setText(s.getName());
                return tv;
            }
        };
        id_flowlayout.setAdapter(tagAdapter);

        id_flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {

                if(When==null || !When.equals(DurationInfoList.get(position).getName())){
                    When = DurationInfoList.get(position).getName();
                    ViseLog.d("单选的事件"+When);
                }else{
                    When = DurationInfoList.get(DurationInfoList.size()-1).getName();
                }
                return true;
            }
        });


        //多选
        MultiselectAdapter=new TagAdapter<TroubleInfodb>(TroubleinfoList) {
            @Override
            public View getView(FlowLayout parent, int position, TroubleInfodb s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.tv,
                        id_flowlayout, false);
                tv.setText(s.getName());
                return tv;
            }
        };
        id_multiselect.setAdapter(MultiselectAdapter);
        id_multiselect.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                TroubleName.clear();
                et_custom.setVisibility(View.GONE);
                final String Strcustom = et_custom.getText().toString().trim();
                for (Integer inte : selectPosSet) {
                    String numId = TroubleinfoList.get(inte).getName();
                    ViseLog.d("多选的数据" + numId+Strcustom);
                    if (numId.equals("其他")) {
                        et_custom.setVisibility(View.VISIBLE);
                    }
                    TroubleName.add(numId);

                }
            }

        });
    }

    @Override
    protected void initData() {
        discomfortPresenter = new DiscomfortPresenter(this);
        //查询当日不适症状列表
        discomfortPresenter.PostDiscomfortData(longTime.substring(0,10),longTime.substring(0,10));
    }


    //提交
    @OptionsItem(R.id.action_submit)
    public void action_submit() {

        String describe = et_describe.getText().toString().trim();

        String StrCustom=et_custom.getText().toString().trim();
        for(int i=0;i<TroubleName.size();i++){
            if(TroubleName.get(i).equals("其他")){
                if(StrCustom.length()!=0){
                    TroubleName.set(i,StrCustom);
                }
            }
        }

        //当描述为空时
        if (describe == null || describe.length() == 0) {
            describe = "";
        }

        //Trouble
        List<Trouble> trouble = new ArrayList<>();

        for (int i = 0; i < TroubleName.size(); i++) {
            Trouble tr = new Trouble(TroubleName.get(i));
            trouble.add(tr);
        }

        for(int i=0;i<discomfortDataList.size();i++){

            for(int a=0;a<trouble.size();a++){
                if(trouble.get(a).getTroubleName().equals(discomfortDataList.get(i).getTroubleName())){
                    msg("当天\t"+trouble.get(a).getTroubleName()+"\t已存在");
                    return;
                }
            }
        }

        //当症状描述和不适时长未选择时默认为最后一个数据
        if (TroubleName.size() == 0) {
            Trouble tr = new Trouble(TroubleinfoList.get(TroubleinfoList.size() - 1).getName());
            trouble.add(tr);
        }
        if (When == null) {
            When = DurationInfoList.get(DurationInfoList.size() - 1).getName();
        }

        if (TroubleName.size() == 0) {
            msg("请选择不适症状");
            return;
        }

        //不适症状
        String json = JSON.toJSONString(trouble);
        ViseLog.d("上传的不是症状信息"+json);
        //不适时长，描述信息,不适症状列表
        discomfortPresenter.AddTroubleDetailPost(describe, json, longTime, When);
    }

    List<DiscomfortData> discomfortDataList = new ArrayList<>();
    @Override
    public void onViewFirstSuccess(AnotherResult<DiscomfortData> data) {
        discomfortDataList.clear();
        if (data.getList().size() != 0) {
            DiscomfortData discomfortData = new DiscomfortData();
            discomfortData.setItemType(DiscomfortData.HEAD);
            discomfortDataList.add(discomfortData);
        }

        int size = data.getList().size();
        //只显示5条数据
        if (size > 5) {
            size = 5;
        }

        for (int i = 0; i < size; i++) {
            DiscomfortData discomfort = new DiscomfortData();
            discomfort.setItemType(DiscomfortData.BODY);
            discomfort.setDescription(data.getList().get(i).getDescription());
            discomfort.setDurationId(data.getList().get(i).getDurationId());
            discomfort.setId(data.getList().get(i).getId());
            discomfort.setLogTime(data.getList().get(i).getLogTime());
            discomfort.setTroubleId(data.getList().get(i).getTroubleId());
            discomfort.setUserId(data.getList().get(i).getUserId());
            discomfort.setTroubleName(data.getList().get(i).getTroubleName());
            discomfort.setDurationLength(data.getList().get(i).getDurationLength());
            discomfortDataList.add(discomfort);
        }
        initAdapter(discomfortDataList);
    }

    @Override
    public void onViewNextSuccess(AnotherResult<DiscomfortData> data) {
    }

    @Override
    public void onViewError(String msg) {
        if (msg != null) {
            msg(msg);
        }
    }

    @Override
    public void onViewRefreshUI() {

    }

    @Override
    public void onSubSymptoms(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            msg("提交成功");
            //查询当日不适症状列表
            discomfortPresenter.PostDiscomfortData(longTime.substring(0,10),longTime.substring(0,10));
            et_describe.setText("");
            tagAdapter.setSelectedList();//提交完成后清空选中的数据
            MultiselectAdapter.setSelectedList();
            TroubleName.clear();
        }
    }

    @Override
    public void onViewRefreshListSuccess() {
        eventAdapter.notifyDataSetChanged();
    }

    //修改事件信息
    @Override
    public void onUpdateDescribe(DataStateResult dataStateResult) {

    }

    //初始化adapter布局
    public void initAdapter(List<DiscomfortData> data) {
        eventAdapter = new EventAdapter(data);
        rv_list.setAdapter(eventAdapter);

        eventAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    //修改描述
                    case R.id.demo:
                        DiscomfortData discomfortData=eventAdapter.getItem(position);
                        if(discomfortData.getTroubleName()!=null && discomfortData.getTroubleName().length()>0){
                            dialogView(discomfortData);
                        }
                        break;
                        //修改时长id

                    case R.id.msgcheck:
                        DiscomfortData discomfort=eventAdapter.getItem(position);
                        if(discomfort.getDurationLength()!=null && discomfort.getDurationLength().length()>0){
                            whenLongDialog(discomfort);
                        }
                        break;
                }
            }
        });

        eventAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {

                switch (view.getId()){
                    case R.id.msg:
                        DiscomfortData discomfortData=eventAdapter.getItem(position);
                        ViseLog.d("删除事件");
                        dialogdelete(discomfortData);
                        break;
                }
                return false;
            }
        });
    }

    //删除事件

    public void dialogdelete(final DiscomfortData discomfortData) {

        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                discomfortPresenter.DeleteEvent(discomfortData.getId()+"");
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.title("确认删除\t"+discomfortData.getTroubleName()+"\t这条事件吗？")
                .positiveAction("确定")
                .negativeAction("取消");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }

    //选择时长
    public void whenLongDialog(final DiscomfortData discomfort){

        final String [] longStr=new String[DurationInfoList.size()];
        for(int i=0;i<DurationInfoList.size();i++){
            longStr[i]=DurationInfoList.get(i).getName();
        }

        SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {

                int index = getSelectedIndex();
                String strVal=longStr[index];

                discomfortPresenter.AmmTroubleDetailServer(
                        discomfort.getTroubleName(),
                        strVal,
                        discomfort.getLogTime(),
                        discomfort.getDescription(),
                        discomfort.getId()+""
                );
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };

        int indexDurationLength=0;
        for(int i=0;i<DurationInfoList.size();i++){
            if(DurationInfoList.get(i).getName().equals(discomfort.getDurationLength())){
                indexDurationLength=i;
                break;
            }
        }

        ((SimpleDialog.Builder) builder).items(longStr, indexDurationLength)
                .title("选择不适时常")
                .positiveAction("确认")
                .negativeAction("取消");
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(this.getSupportFragmentManager(), null);

    }


    public void dialogView(final DiscomfortData discomfortData){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        View views = LayoutInflater.from(this).inflate(R.layout.dialog_edit_describe, null);
        Toolbar main_toolbar = (Toolbar) views.findViewById(R.id.main_toolbar);
        main_toolbar.setTitle("描述");
        dialog.setView(views);
        final android.widget.EditText edit_min = (android.widget.EditText) views.findViewById(R.id.edit_detection);
        edit_min.setText(discomfortData.getDescription());
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String Description=edit_min.getText().toString();
                discomfortPresenter.AmmTroubleDetailServer(
                        discomfortData.getTroubleName(),
                        discomfortData.getDurationLength(),
                        discomfortData.getLogTime(),
                        Description,
                        discomfortData.getId()+""
                        );
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }
}
